<template>
  <div class="login-container">
    <!-- 左侧宣传图 -->
    <div class="login-banner">
      <div class="banner-content">
        <h2>菜购生鲜管理系统</h2>
        <p>高效管理订单、库存与配送，让每一份新鲜准时送达</p>
        <div class="veg-icon">
          🥦 🥬 🍅 🥕 🧄
        </div>
      </div>
    </div>

    <!-- 右侧登录表单 -->
    <div class="login-form">
      <div class="logo">
        <i class="el-icon-leaf" style="color: #4caf50; font-size: 36px;"></i>
        <h1>菜购后台</h1>
        <p>只为更鲜更快</p>
      </div>

      <el-form
          ref="loginForm"
          :model="form"
          :rules="rules"
          @submit.native.prevent="handleLogin"
      >
        <!-- 账号 -->
        <el-form-item prop="username">
          <el-input
              v-model="form.username"
              :prefix-icon="User"
              placeholder="请输入账号（如：admin）"
              clearable
              @keyup.enter.native="handleLogin"
          />
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
              v-model="form.password"
              type="password"
              :prefix-icon="Lock"
              placeholder="请输入密码"
              show-password
              @keyup.enter.native="handleLogin"
          />
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item prop="captchaCode">
          <el-input
              v-model="form.captchaCode"
              :prefix-icon="Verification"
              placeholder="请输入验证码"
              @keyup.enter.native="handleLogin"
              style="width: 65%;"
          />
          <div class="captcha-image-container">
            <img
                :src="captchaImage"
                alt="验证码"
                class="captcha-image"
                @click="refreshCaptcha"
            >
            <span class="refresh-text" @click="refreshCaptcha">换一张</span>
          </div>
        </el-form-item>

        <!-- 记住我 + 忘记密码 -->
        <div class="form-options">
          <el-checkbox v-model="form.remember">记住我</el-checkbox>
          <a href="#" class="forgot">忘记密码？</a>
        </div>

        <!-- 登录按钮 -->
        <el-form-item>
          <el-button
              type="success"
              :loading="loading"
              @click="handleLogin"
              style="width: 100%; font-size: 16px; padding: 12px;"
          >
            {{ loading ? '登录中...' : '登 录' }}
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 错误提示 -->
      <div v-if="error" class="error-message">
        <i class="el-icon-warning"></i> {{ error }}
      </div>

      <!-- 底部版权 -->
      <div class="footer">
        &copy; 2025 采购生鲜科技有限公司. 保留所有权利.
      </div>
    </div>
  </div>
</template>

<script>
import {Lock, User} from '@element-plus/icons-vue'
import {getCaptcha, login} from "../api/login.js";

let RefreshCw;
export default {
  name: 'Login',
  components: {
    RefreshCw
  },
  computed: {
    Lock() {
      return Lock
    },
    User() {
      return User
    },
    Verification() {
      return RefreshCw // 使用刷新图标作为验证码图标
    }
  },
  data() {
    return {
      form: {
        username: '',
        password: '',
        captchaCode: '',
        remember: false
      },
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不少于6位', trigger: 'blur' }
        ],
        captchaCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { min: 4, max: 4, message: '验证码长度为4位', trigger: 'blur' }
        ]
      },
      loading: false,
      error: '',
      captchaImage: '',
      captchaKey: '',
      captchaCode: '',
      captchaLoading: false
    }
  },
  created() {
    // 页面加载时获取验证码
    this.refreshCaptcha();

    // 如果记住密码，填充表单
    if (sessionStorage.getItem('remember') === 'true') {
      this.form.remember = true;
      // 这里可以从localStorage获取保存的用户名密码
      // this.form.username = localStorage.getItem('username') || '';
      // this.form.password = localStorage.getItem('password') || '';
    }
  },
  methods: {
    // 获取验证码
    async refreshCaptcha() {
      this.captchaLoading = true;
      try {
        const { data } = await getCaptcha();
        if (data.code === 200) {
          this.captchaImage = data.data.captchaImage;
          console.log('captchaImage', this.captchaImage)
          this.captchaKey = data.data.captchaKey;
        } else {
          this.$message.error(data.msg || '获取验证码失败，请重试');
        }
      } catch (error) {
        console.error('获取验证码失败:', error);
        this.$message.error('获取验证码失败，请重试');
      } finally {
        this.captchaLoading = false;
      }
    },

    async handleLogin() {
      await this.$refs.loginForm.validate(async (valid) => {
        if (!valid) return;

        this.loading = true;
        this.error = '';

        try {
          // 准备登录参数，包含验证码信息
          const loginParams = {
            ...this.form,
            captchaKey: this.captchaKey
          };

          // 调用登录接口
          const { data } = await login(loginParams);

          if (data.code === 1000) {
            // 存储token
            sessionStorage.setItem('token', data.data.token);

            // 处理记住密码
            if (this.form.remember) {
              sessionStorage.setItem('remember', 'true');
              // 可选：如果需要长期记住，可将账号密码存入localStorage
              // localStorage.setItem('username', this.form.username);
              // localStorage.setItem('password', this.form.password);
            } else {
              sessionStorage.removeItem('remember');
              // localStorage.removeItem('username');
              // localStorage.removeItem('password');
            }

            // 登录成功提示并跳转
            this.$message({
              message: '欢迎回来,亲爱的魁拔！',
              type: 'success'
            });
            this.$router.push('/');
          } else {
            // 登录失败，刷新验证码
            await this.refreshCaptcha();
            // 显示错误信息
            this.error = data.msg || '登录失败，请重试';
            this.$message.error(this.error);
          }
        } catch (error) {
          // 捕获网络错误或接口异常
          await this.refreshCaptcha();
          this.error = '登录请求失败，请检查网络';
          this.$message.error(this.error);
          console.error('登录接口异常:', error);
        } finally {
          this.loading = false;
        }
      });
    }
  },
  // 页面加载时获取验证码
  mounted() {
     this.refreshCaptcha();
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  height: 100vh;
  font-family: 'Helvetica Neue', Arial, sans-serif;
}

/* 左侧宣传区 */
.login-banner {
  flex: 1;
  background: linear-gradient(to bottom, #4caf50, #8bc34a);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 20px;
}

.banner-content h2 {
  font-size: 28px;
  margin: 0 0 12px;
}

.banner-content p {
  font-size: 15px;
  opacity: 0.9;
  max-width: 300px;
  margin: 0 auto 20px;
}

.veg-icon {
  font-size: 24px;
  letter-spacing: 10px;
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-10px); }
}

/* 右侧登录区 */
.login-form {
  width: 420px;
  padding: 50px 40px;
  background: white;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.logo {
  text-align: center;
  margin-bottom: 30px;
}

.logo h1 {
  margin: 10px 0 0;
  font-size: 26px;
  color: #2e7d32;
  font-weight: 600;
}

.logo p {
  color: #666;
  font-size: 14px;
  margin-top: 6px;
}

/* 验证码样式 */
.captcha-image-container {
  display: inline-block;
  width: 33%;
  margin-left: 2%;
  vertical-align: middle;
}

.captcha-image {
  width: 100%;
  height: 40px;
  border-radius: 4px;
  cursor: pointer;
  vertical-align: middle;
}

.refresh-text {
  display: block;
  font-size: 12px;
  color: #4caf50;
  text-align: center;
  margin-top: 5px;
  cursor: pointer;
}

.refresh-text:hover {
  text-decoration: underline;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  font-size: 14px;
}

.forgot {
  color: #4caf50;
  text-decoration: none;
}

.forgot:hover {
  text-decoration: underline;
}

.error-message {
  padding: 12px;
  background: #fdecea;
  color: #e74c3c;
  border: 1px solid #f5c6c1;
  border-radius: 8px;
  font-size: 14px;
  text-align: center;
  margin: 16px 0;
}

.error-message i {
  margin-right: 4px;
}

.footer {
  margin-top: auto;
  text-align: center;
  font-size: 12px;
  color: #999;
  padding-top: 20px;
}

/* 响应式：移动端适配 */
@media (max-width: 768px) {
  .login-container {
    flex-direction: column;
  }
  .login-banner {
    padding: 30px 20px;
  }
  .login-banner h2 {
    font-size: 24px;
  }
  .login-form {
    width: 100%;
    max-width: 400px;
  }

  .captcha-image-container {
    width: 30%;
  }
}
</style>
